<?php 
## include required files
/*******************************/
require_once '../../includefiles.php';
include_once("../../model/users.php");
include_once("../../model/trade.php");
include_once("../../model/leads.php");
include_once("../../model/state.php");
require_once '../../model/city.php';
include_once("../../model/budget.php");
include_once '../../model/paypal.php';
include_once '../../model/nab.php';
include_once("../../model/usermembership.php");
include_once("../../model/usermembershipdetail.php");
require_once '../../model/membershipplan.php';
require_once '../../model/admindetails.php';
include_once '../../model/email.php';
require_once '../../includes/classes/paypalfunction.php'; // Pay Pal pro Function file 
require_once '../../redirect.php';



$userObj = new Model_Users();
$tradeObj = new Model_TRADE();
$leadObj = new Model_Leads();
$objState = new Model_State();
$objCity = new Model_City();
$budgetObj = new Model_Budget();
$paypalObj = new Model_Paypal();
$memberObj	= new Model_Membership();
$memberDetailObj	= new Model_MembershipDetail();
$objPlan = new Model_PLAN();
$adminObj = new Model_AdminDetails();
$emailObj = new Model_Email();
$Model_NAB = new Model_NAB();

$objNAB = $Model_NAB->getDetail();

if(!$_SESSION['payment'])
{
	redirect_to_link(SITE_URL);
	exit;	
}	
$payVars = $_SESSION['payment'];
$userId = $_SESSION['getbids_id'];

$postjobid = base64_decode($payVars['jobid']);	
// job detail	
$jobdetArray = $userObj->getJobDetailsById($postjobid);
// trade detail
$gettradedetail = $tradeObj->getTradeCategoryDetailsById($jobdetArray['trade_id']);	
//jobtype detail
$getjobtypedetail = $tradeObj->getTradeCategoryDetailsById($jobdetArray['jobtype_id']);
// homeowner detail
$homeowneruserDetArray = $userObj->getUserDetailsByUserId($jobdetArray['user_id']);
//tradesman detail 
$userDetArray = $userObj->getUserDetailsByUserId($userId);


$total = $_SESSION['payment']['cost'] + ($_SESSION['payment']['cost'] * $objNAB['tax'] )/100;
$invoiceId = $payVars['invoiceid'];

if($payVars['paymentmethod'] == "paypal")
{

	if($_POST['auth'] && $_POST['verify_sign'] && $_POST['receiver_id'] && $_POST['payment_status'] == 'Completed')
	{
		//store order
		/************ Add record to membership plan Table ************/
		//$finalTotal = $_POST['mc_gross'];
		$finalTotal = $_SESSION['payment']['cost'];
		$membershipArray = array();
		$membershipArray['amount'] = $_POST['mc_gross'];
		$membershipArray['user_id'] = $userId;
		$membershipArray['dateadded'] = date("Y-m-d H:i:s");
		$orderId = $memberObj->addOrder($membershipArray);
		
		$membershipplanArray 				    = 		array();	
		$membershipplanArray['user_id'] 		= 		$userId;
		$membershipplanArray['mem_id'] 			= 		$orderId;
		$membershipplanArray['plan_id'] 		= 		$payVars['plan_id'];	
		$membershipplanArray['amount'] 	    	= 		$finalTotal;
		$membershipplanArray['add_date']   		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status_date'] 	= 		date("Y-m-d H:i:s");
		$invoiceId 								= 		$invoiceId;
		$orderCardArray['invoiceid']			= 		$invoiceId;
		$transactionId 							= 		$payVars['payer_id'];
		$membershipplanArray['transaction_id']  =       $transactionId;	
		//$membershipplanArray['transaction_msg'] =       $httpParsedResponseAr["L_LONGMESSAGE0"];	 			
		$membershipplanArray['invoiceid']       =       $invoiceId;	
		$membershipplanArray['status_date']		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status'] 			= 		"paid";
		
		$membershipplanArray['total'] 			= 		$total;
		$membershipplanArray['pmethod'] 			= 		"Paypal";
		
		if($payVars['membershipplan']!='')
			$membershipplanArray['paymentfor'] 			= 		"membershipplan";
		else
			$membershipplanArray['paymentfor'] 			= 		"leadprice";
			
		$orderDealId 			    			= 		$memberDetailObj->addRecord($membershipplanArray); // add order

		if($payVars['membershipplan']!='')
		{
			// code for update user leads
			$getplandetails = $objPlan->getPlanDetailsById($payVars['plan_id']);
			$userArray = array();
			// expiry incremented
			$todaydate = date('Y-m-d');
			$exp_todaydate = explode('-',$todaydate);
			$userArray['expiry_date'] = date('Y-m-d',mktime(0,0,0,$exp_todaydate[1]+$getplandetails['month'],$exp_todaydate[2],$exp_todaydate[0]));
			$userArray['leads']	= $getplandetails['leads']-1;
			$userObj->editUserValueById($userArray,$userId);	
		}
		//update lead
		$userJobViewArray["userid"] 	= $userId;					
		$userJobViewArray["jobid"] 		= $postjobid;
		$userJobViewArray["message"] 		= $payVars['message'];
		$userJobViewArray["date_added"] = date('Y-m-d');
		$jobviewId = $userObj->addUserViewJOBByValue($userJobViewArray);
			
		// code for update user leads
		$getplandetails = $objPlan->getPlanDetailsById($payVars['plan_id']);
		//mae invoice pdf		
		


		$files = makeInvoicePDF($userId,$orderDealId);
		//email to admin
		mailtoAdmin($emailObj,$userDetArray,$jobdetArray,$payVars,$homeowneruserDetArray,$adminObj,$files);
		//email to tradesman
		mailtoTradesman($emailObj,$userDetArray,$gettradedetail,$jobdetArray,$payVars,$homeowneruserDetArray,$adminObj,$files);
		

		//unset($_SESSION['payment']);

		if($payVars['membershipplan']!='')
			$_SESSION['msg'] = "<div class='success_msg'><span>Your membership plan has been renewed !</span></div>";
		else	
			$_SESSION['msg'] = "<div class='success_msg'><span>You have paid successfully lead price !</span></div>";
		header('location:'.SITE_URL.'/leads/');
		exit;	
					
	}
	else
	{
		unset($_SESSION['payment']);
		$_SESSION['msg'] = "<div class='success_msg'><span>Payment declined !</span></div>";
		header('location:'.SITE_URL.'/leads/');
		exit;
	}
}

//NAB
if($_REQUEST['refid'] && $_REQUEST['rescode']  && $_REQUEST['restext']  && $_REQUEST['settdate']  && $_REQUEST['txnid']  && $_REQUEST['sig'] )
{



	if($_REQUEST['rescode'] == "00" || $_REQUEST['rescode'] =="08")
	{
		//success	
		$finalTotal = $_SESSION['payment']['cost'];
		$membershipArray = array();
		$membershipArray['amount'] = $_POST['mc_gross'];
		$membershipArray['user_id'] = $userId;
		$membershipArray['dateadded'] = date("Y-m-d H:i:s");
		$orderId = $memberObj->addOrder($membershipArray);
		
		$membershipplanArray 				    = 		array();	
		$membershipplanArray['user_id'] 		= 		$userId;
		$membershipplanArray['mem_id'] 			= 		$orderId;
		$membershipplanArray['plan_id'] 		= 		$payVars['plan_id'];	
		$membershipplanArray['amount'] 	    	= 		$finalTotal;
		$membershipplanArray['add_date']   		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status_date'] 	= 		date("Y-m-d H:i:s");
		$invoiceId 								= 		$invoiceId;
		$orderCardArray['invoiceid']			= 		$invoiceId;
		$transactionId 							= 		$_POST['payer_id'];
		$membershipplanArray['transaction_id']  =       $transactionId;	
		//$membershipplanArray['transaction_msg'] =       $httpParsedResponseAr["L_LONGMESSAGE0"];	 			
		$membershipplanArray['invoiceid']       =       $invoiceId;	
		$membershipplanArray['status_date']		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status'] 			= 		"paid";
		$membershipplanArray['total'] 			= 		$total;
		$membershipplanArray['pmethod'] 			= 		"NAB";
		
		
		if($payVars['membershipplan']!='')
			$membershipplanArray['paymentfor'] 			= 		"membershipplan";
		else
			$membershipplanArray['paymentfor'] 			= 		"leadprice";
		$orderDealId 			    			= 		$memberDetailObj->addRecord($membershipplanArray); // add order

		if($payVars['membershipplan']!='')
		{
			// code for update user leads
			$getplandetails = $objPlan->getPlanDetailsById($payVars['plan_id']);
			$userArray = array();
			// expiry incremented
			$todaydate = date('Y-m-d');
			$exp_todaydate = explode('-',$todaydate);
			$userArray['expiry_date'] = date('Y-m-d',mktime(0,0,0,$exp_todaydate[1]+$getplandetails['month'],$exp_todaydate[2],$exp_todaydate[0]));
			$userArray['leads']	= $getplandetails['leads']-1;
			$userObj->editUserValueById($userArray,$userId);	
		}
		//update lead
		$userJobViewArray["userid"] 	= $userId;					
		$userJobViewArray["jobid"] 		= $postjobid;
		$userJobViewArray["message"] 		= $payVars['message'];
		$userJobViewArray["date_added"] = date('Y-m-d');
		$jobviewId = $userObj->addUserViewJOBByValue($userJobViewArray);
			
		
		//mae invoice pdf		
		$files = makeInvoicePDF($userId,$orderDealId);		
		//email to admin
		mailtoAdmin($emailObj,$userDetArray,$jobdetArray,$payVars,$homeowneruserDetArray,$adminObj,$files);
		//email to tradesman
		mailtoTradesman($emailObj,$userDetArray,$gettradedetail,$jobdetArray,$payVars,$homeowneruserDetArray,$adminObj,$files);
		
		unset($_SESSION['payment']);

		if($payVars['membershipplan']!='')
			$_SESSION['msg'] = "<div class='success_msg'><span>Your membership plan has been renewed !</span></div>";
		else	
			$_SESSION['msg'] = "<div class='success_msg'><span>You have paid successfully lead price !</span></div>";
		header('location:'.SITE_URL.'/leads/');
		exit;	
					
	}
	else //decline
	{
		unset($_SESSION['payment']);
		$_SESSION['msg'] = "<div class='success_msg'><span>Payment declined !</span></div>";
		header('location:'.SITE_URL.'/leads/');
		exit;
	}
		
}

function mailtoAdmin($emailObj,$userDetArray,$jobdetArray,$payVars,$homeowneruserDetArray,$adminObj,$files)
{
	// send email message admin
	$email_message = $emailObj->getEmailById(11);
	$e_subject = $email_message['email_subject'];
	$message = $email_message['email_content']; 
	
	$subject = str_replace('[NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $e_subject);		 
	
	$message = str_replace('[NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $message);
	$message = str_replace('[SITENAME]', SITENAME, $message);
	$message = str_replace('[TRADE]', trim($gettradedetail["trade_category"]), $message);
	$message = str_replace('[JOBTYPE]', trim($getjobtypedetail["trade_category"]), $message); 
	$message = str_replace('[JOBDESC]', trim($jobdetArray["job_desc"]), $message); 
	$message = str_replace('[HOME_NAME]', trim($homeowneruserDetArray["first_name"])." ".trim($homeowneruserDetArray["last_name"]) , $message);
	$message = str_replace('[TRADE_NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $message);
	
	
	$adminEmail = $adminObj->getAdminDetails();
	$to = $adminEmail;
	$from = $adminEmail;
	$fromname= SITENAME;
					 
	$emailTemplate = file_get_contents('../../emailtemplate.html');
	$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
	$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
	$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
	if(trim($to) != '')
	{
		//@send_mail($to, $template_msg, $subject, $from, $fromname);  
		$mailer = new AttachMailer($from,$to, $subject, $template_msg);
		$mailer->attachFile($files[0].$files[1]);
		$mailer->send();

	}
}

function mailtoTradesman($emailObj,$userDetArray,$gettradedetail,$jobdetArray,$payVars,$homeowneruserDetArray,$adminObj,$files)
{
	// send email message to Tradesman user 
	$email_message = $emailObj->getEmailById(12);
	$e_subject = $email_message['email_subject'];
	$message = $email_message['email_content']; 
	
	$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		 
			
	$message = str_replace('[TRADE]', trim($gettradedetail["trade_category"]), $message);
	$message = str_replace('[JOBTYPE]', trim($getjobtypedetail["trade_category"]), $message); 
	$message = str_replace('[JOBDESC]', trim($jobdetArray["job_desc"]), $message); 
	$message = str_replace('[JOBPOSTCODE]', trim($jobdetArray["area"]), $message); 
	$message = str_replace('[HOME_NAME]', trim($homeowneruserDetArray["first_name"])." ".trim($homeowneruserDetArray["last_name"]) , $message);
	$message = str_replace('[HOME_EMAIL]', trim($homeowneruserDetArray["email"]), $message);
	$message = str_replace('[HOME_MOBNO]', trim($homeowneruserDetArray["phone_number"]), $message);
	$message = str_replace('[SITENAME]', SITENAME, $message);
	


	$to= trim($userDetArray["email"]);
	$adminEmail = $adminObj->getAdminDetails();
	$from = $adminEmail;
	$fromname= SITENAME;
					 
	$emailTemplate = file_get_contents('../../emailtemplate.html');
	$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
	$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
	$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 



	if(trim($to) != '')
	{
		//@send_mail($to, $template_msg, $subject, $from, $fromname); 	
		$mailer = new AttachMailer( $from,$to, $subject, $template_msg);
		$mailer->attachFile($files[0].$files[1]);
		$mailer->send();

	}
}

?>

